<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper" v-if="createFormBox">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="4" :sm="24" style="min-width: 230px;">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="请输入姓名/邮箱/手机号" />
            </a-form-item>
          </a-col>
          <div style="float: right;margin-right:24px;">
            <a-button type="primary" icon="plus" size="20" @click="createFormBox=false" v-if="operationPermission['add']">创建账户</a-button>
          </div>
        </a-row>
      </a-form>
      <s-table class="table_style" ref="table" size="default" rowKey="key" :columns="columns" :data="loadData" :alert="options.alert" :rowSelection="options.rowSelection" showPagination="auto">
        <span slot="serial" slot-scope="text,record,index">{{ index + 1 }}</span>
        <span slot="action" slot-scope="text,record,index" class="operation_button_box">
          <template>
            <a-button size="small" type="primary" @click="handleEdit(record)" class="operation_button_details" v-if="operationPermission['update']">编辑</a-button>
            <button class="operation_button_passwd" @click="handlePassword" v-if="operationPermission['updatePassword']">修改密码</button>
            <!-- <a-button size="small"  class="operation_button_passwd" @click="handleSub(record)">修改密码</a-button> -->
          </template>
        </span>
      </s-table>
    </div>
    <div v-else>

      <h3 class="create_form_title">创建账户</h3>
      <list-form :roles="roles" :companies="companies" @ok="handleOk" @Cancel="handleCancel"></list-form>

    </div>
    <a-modal :width="976" :footer="null" v-model="changePassword" @ok="handleOk">
      <template slot="title">
        <p class="createFormEdit_title">修改密码</p>
      </template>

      <div class="createFormEdit_content">
        <a-form :form="form">

          <a-form-item label="旧密码">
            <a-input type="password" v-decorator="['oldPassword', { rules: [{ required: true, message: '请输入旧密码!' }] }]" placeholder="请输入旧密码" />
          </a-form-item>
          <a-form-item label="新密码">
            <a-input v-decorator="['newPassword', { rules: [{ required: true, message: '请输入新密码!' }] }]" placeholder="请输入新密码" />
          </a-form-item>
          <a-form-item label="确认密码">
            <a-input v-decorator="['newPasswordRepeat', { rules: [{ required: true, message: '请重复输入新密码!' }] }]" placeholder="请重复输入新密码" />
          </a-form-item>

        </a-form>

        <div class="createFormEdit_font_box">
          <div class="createFormEdit_font">
            <a-button size="large" key="cancel" @click="handleCancel" style="margin-left:20px;">取消</a-button>
            <a-button size="large" key="forward" :loading="confirmLoading" type="primary" @click="handleUpdatePassword()" style="margin-left:20px;">确定</a-button>

          </div>
        </div>

      </div>
    </a-modal>
    <a-modal :width="976" :footer="null" v-model="createFormEdit" @ok="handleOk">
      <template slot="title">
        <p class="createFormEdit_title">编辑账户</p>
      </template>

      <div class="createFormEdit_content">
        <a-form :form="form">

          <a-form-item label="姓名">
            <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入账户姓名!' }] }]" placeholder="请输入账户姓名" />
          </a-form-item>
          <a-form-item label="公司">
            <a-select v-decorator="['companyId', { rules: [{ required: true, message: '请输入账户公司!' }] }]" placeholder="请输入账户公司">
              <a-select-option v-for="item in companies" :key="item.companyId" :value="item.companyId">{{ item.companyName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="电子邮箱">
            <a-input v-decorator="['email', { rules: [{ required: true, message: '请输入账户电子邮箱!' }] }]" placeholder="请输入账户电子邮箱" />
          </a-form-item>
          <a-form-item label="手机号">
            <a-input v-decorator="['phone', { rules: [{ required: true, message: '请输入账户的手机号!' }] }]" placeholder="请输入账户的手机号" />
          </a-form-item>
          <a-form-item label="角色">
            <a-select v-decorator="['roleId', { rules: [{ required: true, message: '请输入账户的角色!' }] }]" placeholder="请输入账户的角色">
              <a-select-option v-for="item in roles" :key="item.id" :value="item.id">{{ item.roleName }}</a-select-option>
            </a-select>
          </a-form-item>

        </a-form>

        <div class="createFormEdit_font_box">
          <div class="createFormEdit_font">
            <a-button size="large" key="cancel" @click="handleCancel" style="margin-left:20px;">取消</a-button>
            <a-button size="large" key="forward" :loading="confirmLoading" type="primary" @click="handleUpdate()" style="margin-left:20px;">确定</a-button>

          </div>
        </div>

      </div>
    </a-modal>
    <!-- <test-design @ok="handleOk" ref="modal"></test-design>
    <step-by-step-modal ref="modal" @ok="handleOk" /> -->
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
// import TestDesign from './modules/TestDesign'
import ListForm from './modules/AccountListForm'
import { getCompanyList, getRoleList, getAccountList, postAccountUpdate, postAccountUpdatePassword } from '@/api/manage'

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    ListForm
    // TestDesign
  },
  data () {
    return {
      operationPermission:{},
      createFormEdit: false,
      selectedAccountId: '',
      createFormBox: true,
      changePassword: false,
      confirmLoading: false,
      statusMap: [],
      mdl: {},
      companies: null,
      roles: null,
      // 高级搜索 展开/关闭
      advanced: false,
      form: this.$form.createForm(this),
      // 查询参数
      queryParam: {
        // pageNo: 1,
        // pageSize: 20,
        // totalPage: 1
      },
      // 表头
      visible: false,
      designArray: {
        '0': '预发布',
        '1': '进行中',
        '2': '暂停中',
        '3': '已结束'
      },
      columns: [
        {
          title: '序号',
          // dataIndex: 'id',
          scopedSlots: { customRender: 'serial' },
          align: 'center'
        },
        {
          title: '姓名',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '公司',
          dataIndex: 'company',
          align: 'center'
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          // needTotal: true,
          // customRender: (text) => text + ' 次',
          align: 'center'
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          align: 'center'
        },
        {
          title: '角色',
          dataIndex: 'roleName',
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'statusName',
          // scopedSlots: { customRender: 'statusName' },
          align: 'center'
        },
        // {
        //   // title: '发布时间',
        //   // dataIndex: 'updatedAt',
        //   // align:'center'

        //   dataIndex: 'updatedAt',
        //   key: 'updatedAt',
        //   slots: { title: 'customTitle' },
        //   scopedSlots: { customRender: 'updatedAt' },
        //   // sorter: true,
        //   align: 'center'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          width: '200px',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        // debugger
        return getAccountList(Object.assign(parameter, this.queryParam))
          .then(res => {
            // debugger
            console.log(res.data.message)
            res.data.data = res.data.list
            return res.data
            // return res.data.list
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true
    }
  },
  filters: {
    statusFilter (type) {
      // return statusMap[type].text
    },
    statusTypeFilter (type) {
      // return statusMap[type].status
    }
  },
  created () {
    let list = JSON.parse(localStorage.getItem("operationPermission"))
    list.forEach(element => {
      if (element.permissionId == 'accountList') { 
        element.actionVOS.forEach(i => {
          this.operationPermission[i.action] = i.defaultCheck
        });
      }
    });
    console.log(this.operationPermission,"ggggg")
    // getRoleList({ t: new Date() })
    // getAccountList()
    this.tableOption()
    this.getRoleList()
    this.getCompanyList()
  },
  methods: {
    getRoleList () {
      getRoleList().then(res => {
        console.log(res.message)
        this.roles = res.data.list
        // return res.data
      })
    },
    getCompanyList () {
      getCompanyList().then(res => {
        console.log(res.message)
        this.companies = res.data
        // return res.data
      })
    },
    CreateFormHandleCancel () {
      this.createFormBox = true
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: record.no === 'No 2', // Column configuration not to be checked
                name: record.no
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleCancel () {
      this.createFormEdit = false
      this.confirmLoading = false
      this.createFormBox = true
      this.changePassword = false
    },
    handleUpdatePassword () {
      // this.confirmLoading = true
      // this.createFormEdit = false

      // eslint-disable-next-line handle-callback-err
      this.form.validateFields((err, values) => {
        console.log(values)

        if (!values) {
          return
        }

        if (!values['oldPassword'] || !values['newPassword'] || !values['newPasswordRepeat']) {
          return
        }

        // this.confirmLoading = true
        // this.createFormEdit = false
        // this.confirmLoading = true
        const oldPassword = values['oldPassword']
        const newPassword = values['newPassword']
        const newPasswordRepeat = values['newPasswordRepeat']

        if (newPassword !== newPasswordRepeat) {
          this.$message.error('两次密码不一致！')
          return
        }

        const body = {
          oldPassword: oldPassword,
          newPassword: newPassword
        }

        // debugger
        this.confirmLoading = true
        postAccountUpdatePassword(body).then(res => {
          this.confirmLoading = false
          if (res.code === 200) {
            this.$message.success(res.message)
            this.changePassword = false
          } else {
            this.$message.error(res.message)
          }
          // console.log(res.message)
          // this.roles = res.data
          // debugger
          // this.selectedRoles = res.data.roles
          // return res.data
          // this.changePassword = false
          // this.confirmLoading = false
          // this.$refs.table.refresh(true)
        })
      })
    },
    handleUpdate () {
      // this.confirmLoading = true
      // this.createFormEdit = false

      // eslint-disable-next-line handle-callback-err
      this.form.validateFields((err, values) => {
        console.log(values)

        if (!values) {
          return
        }

        if (!values['name'] || !values['companyId'] || !values['phone'] || !values['email'] || !values['roleId']) {
          return
        }

        // this.confirmLoading = true
        // this.createFormEdit = false
        this.confirmLoading = true
        const name = values['name']
        const companyId = values['companyId']
        const phone = values['phone']
        const email = values['email']
        const roleId = values['roleId']

        const body = {
          id: this.selectedAccountId,
          name: name,
          companyId: companyId,
          phone: phone,
          email: email,
          roleId: roleId
        }

        postAccountUpdate(body).then(res => {
          console.log(res.message)
          // this.roles = res.data
          // this.selectedRoles = res.data.roles
          // return res.data
          // this.createFormEdit = false
          this.confirmLoading = false
          if (res.code === 200) {
            this.$message.success(res.message)
            this.createFormEdit = false
            this.$refs.table.refresh(true)
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    handlePassword () {
      this.changePassword = true
      setTimeout(() => {
        this.form.setFieldsValue({ oldPassword: '' })
        this.form.setFieldsValue({ newPassword: '' })
        this.form.setFieldsValue({ newPasswordRepeat: '' })
      }, 100)
    },
    handleEdit (record) {
      this.createFormEdit = true
      this.selectedAccountId = record.id
      // console.log(record)
      // this.$refs.modal.edit(record)
      let companyId = ''
      for (const company in this.companies) {
        if (record.company === this.companies[company].companyName) {
          companyId = this.companies[company].companyId
          break
        }
      }

      let roleId = ''
      for (const role in this.roles) {
        if (record.roleName === this.roles[role].roleName) {
          roleId = this.roles[role].id
          break
        }
      }

      setTimeout(() => {
        this.form.setFieldsValue({ name: record.name })
        this.form.setFieldsValue({ companyId: companyId })
        this.form.setFieldsValue({ phone: record.phone })
        this.form.setFieldsValue({ email: record.email })
        this.form.setFieldsValue({ roleId: roleId })
      }, 100)
    },
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk () {
      this.createFormEdit = false
      this.confirmLoading = false
      this.createFormBox = true
      this.changePassword = false
      this.$refs.table.refresh()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    tableStatusEvent (v) {
      // console.log(this.$refs.tableStatusEvent,"徐强ggg")
      // this.$refs.tableStatusEvent.onclick
      // this.visible = false
      console.log(this.visible, '徐强')
      // },
      // getAccountList () {
      //   getAccountList(this.queryParam).then(res => {
      //     this.testDataList = res.data.list
      //     console.log(this.testDataList, '徐强是啊还是')
      //   })
    }
  },
  watch: {
    queryParam: {
      handler (newValue, oldValue) {
        this.$refs.table.refresh(true)
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
.table_status {
  margin: 5px;
}
.ant-popover-title {
  width: 98px;
  height: 22px;
  font-size: 14px;
  font-family: PingFangSC-Regular, Microsoft Yahei, sans-serif;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
}
.createFormEdit_title {
  font-size: 24px;
  font-family: PingFangSC-Medium, Microsoft Yahei, sans-serif;
  font-weight: 700;
  color: rgba(0, 0, 0, 0.85);
  line-height: 24px;
  margin: 0px;
}

.createFormEdit_title_box {
  margin-top: -30px;
}
.createFormEdit_font_box {
  height: 50px;
  .createFormEdit_font {
    float: right;
  }
}

.create_form_title {
  font-size: 24px;
  font-weight: bold;
  color: rgba(74, 74, 74, 1);
  line-height: 22px;
}

.ant-popover-inner-content {
  padding: 5px 10px;
}
.table_status_box:hover {
  background: red;
}
.popover_hint {
  background: red;
}
.operation_button_box {
  padding: 0px;
}
.operation_button_details {
  width: 74px;
  height: 32px;
}
.operation_button_release {
  width: 74px;
  height: 32px;
  margin-left: 10px;
  border: 1px #56ced1 solid;
}
.operation_button_release span {
  color: #56ced1;
}
.operation_button_release:hover {
  background: #c9eced;
  opacity: 0.8;
  border-color: #c9eced;
}

.operation_button_passwd {
  width: 74px;
  height: 32px;
  margin-left: 10px;
  border: 0px #ee7272 solid;
  background: #ee7272 !important;
  color: #fff;
  padding: 0 7px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  outline: none;
}
.operation_button_passwd:hover {
  border: 1px #ee7272 solid !important;
  background: #ee7272;
  opacity: 0.8;
}
</style>
